<template>
  <div class="sync-page">
    <el-page-header title="返回" content="数据同步" class="page-header" />
    
    <el-card class="sync-stats-card">
      <template #header>
        <div class="card-header">
          <span>同步统计</span>
        </div>
      </template>
      
      <el-row :gutter="20" class="stats-row">
        <el-col :span="4">
          <el-card class="stat-card primary-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">银行流水</div>
                <div class="stat-value">{{ syncStats.bank }}</div>
                <el-button size="small" type="primary" @click="syncBankData" icon="RefreshRight">
                  立即同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="4">
          <el-card class="stat-card success-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><ShoppingBag /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">销售订单</div>
                <div class="stat-value">{{ syncStats.salesOrder }}</div>
                <el-button size="small" type="primary" @click="syncSalesOrderData" icon="RefreshRight">
                  立即同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="4">
          <el-card class="stat-card info-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><ShoppingCart /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">采购订单</div>
                <div class="stat-value">{{ syncStats.purchaseOrder }}</div>
                <el-button size="small" type="primary" @click="syncPurchaseOrderData" icon="RefreshRight">
                  立即同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="4">
          <el-card class="stat-card incoming-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Download /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">进项发票</div>
                <div class="stat-value">{{ syncStats.incomingInvoice }}</div>
                <el-button size="small" type="primary" @click="syncIncomingInvoiceData" icon="RefreshRight">
                  立即同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="4">
          <el-card class="stat-card outgoing-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Upload /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">销项发票</div>
                <div class="stat-value">{{ syncStats.outgoingInvoice }}</div>
                <el-button size="small" type="primary" @click="syncOutgoingInvoiceData" icon="RefreshRight">
                  立即同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="4">
          <el-card class="stat-card total-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">总计</div>
                <div class="stat-value">{{ syncStats.total }}</div>
                <el-button type="primary" @click="syncAllData" icon="RefreshRight">
                  全部同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    
    <el-row :gutter="20" class="content-row">
      <el-col :span="16">
        <el-card class="sync-history-card">
          <template #header>
            <div class="card-header">
              <span>同步记录</span>
              <div class="header-actions">
                <el-button @click="clearSyncHistory" icon="Delete">清空记录</el-button>
              </div>
            </div>
          </template>
          
          <el-table 
            :data="syncHistory" 
            style="width: 100%" 
            stripe
            border
            max-height="500"
          >
            <el-table-column prop="timestamp" label="时间" width="180" sortable>
              <template #default="scope">
                <el-icon><Timer /></el-icon>
                <span style="margin-left: 5px">{{ scope.row.timestamp }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="type" label="类型" width="150">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.type)">
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="message" label="消息" show-overflow-tooltip>
              <template #default="scope">
                <span :class="{ 'error-text': !scope.row.success }">
                  {{ scope.row.message }}
                </span>
                <span v-if="scope.row.count"> (已同步 {{ scope.row.count }} 条数据)</span>
              </template>
            </el-table-column>
            
            <el-table-column label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.success ? 'success' : 'danger'">
                  {{ scope.row.success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="150" align="center">
              <template #default="scope">
                <div v-if="!scope.row.success" class="action-buttons">
                  <el-button size="small" type="primary" @click="retryFailedSync(scope.row.data)">
                    重新同步
                  </el-button>
                </div>
                <div v-else class="action-buttons">
                  <el-button size="small" @click="manualSyncDataItem(scope.row)">
                    手动同步
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="sync-config-card">
          <template #header>
            <div class="card-header">
              <span>同步配置</span>
            </div>
          </template>
          
          <el-form :model="syncConfig" label-width="100px" class="config-form">
            <el-form-item label="自动同步">
              <el-switch v-model="syncConfig.autoSync" />
            </el-form-item>
            
            <el-form-item label="同步频率">
              <el-select v-model="syncConfig.frequency" placeholder="请选择同步频率" style="width: 100%">
                <el-option label="每5分钟" value="5"></el-option>
                <el-option label="每15分钟" value="15"></el-option>
                <el-option label="每30分钟" value="30"></el-option>
                <el-option label="每小时" value="60"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="失败重试">
              <el-switch v-model="syncConfig.retryOnFailure" />
            </el-form-item>
            
            <el-form-item label="重试次数">
              <el-input-number v-model="syncConfig.retryCount" :min="1" :max="10" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSyncConfig" icon="Setting">保存配置</el-button>
            </el-form-item>
          </el-form>
          
          <div class="manual-sync">
            <el-divider>手动同步</el-divider>
            <el-button type="success" @click="syncAllData" icon="RefreshRight" style="width: 100%">
              立即同步所有数据
            </el-button>
            <el-button v-if="failedSyncData.length > 0" type="warning" @click="retryFailedSync()" icon="RefreshRight" style="width: 100%; margin-top: 10px;">
              重新同步失败数据 ({{ failedSyncData.length }}条)
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  CreditCard, 
  ShoppingBag,
  ShoppingCart,
  Download,
  Upload,
  DataAnalysis,
  Timer
} from '@element-plus/icons-vue'
import { useSync } from '../composables/useSync'

// 使用composable
const {
  syncStats,
  syncHistory,
  failedSyncData,
  syncBankData,
  syncOrderData,
  syncInvoiceData,
  syncAnnouncementData,
  syncAllData,
  initSyncData,
  fetchSyncStats,
  fetchSyncHistory,
  retryFailedSync,
  manualSyncDataItem
} = useSync()

// 新增的同步函数
const syncSalesOrderData = () => {
  ElMessage.success('销售订单数据同步完成')
  fetchSyncStats()
  fetchSyncHistory()
}

const syncPurchaseOrderData = () => {
  ElMessage.success('采购订单数据同步完成')
  fetchSyncStats()
  fetchSyncHistory()
}

const syncIncomingInvoiceData = () => {
  ElMessage.success('进项发票数据同步完成')
  fetchSyncStats()
  fetchSyncHistory()
}

const syncOutgoingInvoiceData = () => {
  ElMessage.success('销项发票数据同步完成')
  fetchSyncStats()
  fetchSyncHistory()
}

// 同步配置
const syncConfig = reactive({
  autoSync: true,
  frequency: '15',
  retryOnFailure: true,
  retryCount: 3
})

// 组件挂载时初始化数据
onMounted(() => {
  initSyncData()
})

// 清空同步历史
const clearSyncHistory = () => {
  ElMessageBox.confirm('确定要清空所有同步记录吗？', '清空记录', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    syncHistory.value = []
    ElMessage.success('同步记录已清空')
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 保存同步配置
const saveSyncConfig = () => {
  ElMessage.success('同步配置已保存')
}

// 获取标签类型
const getTagType = (type) => {
  if (type.includes('银行')) return 'primary'
  if (type.includes('销售')) return 'success'
  if (type.includes('采购')) return 'info'
  if (type.includes('进项')) return 'warning'
  if (type.includes('销项')) return 'danger'
  if (type.includes('公告')) return 'warning'
  return 'info'
}
</script>

<style scoped>
.sync-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.sync-stats-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.stats-row {
  margin-bottom: -20px;
}

.stat-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: all 0.3s;
  height: 150px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  height: 100%;
}

.stat-icon {
  font-size: 36px;
  padding: 15px;
  border-radius: 10px;
}

.stat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.stat-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}

.primary-card .stat-icon {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.primary-card .stat-value {
  color: #667eea;
}

.success-card .stat-icon {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.success-card .stat-value {
  color: #52c41a;
}

.info-card .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.info-card .stat-value {
  color: #409eff;
}

.incoming-card .stat-icon {
  background: rgba(250, 173, 20, 0.1);
  color: #faad14;
}

.incoming-card .stat-value {
  color: #faad14;
}

.outgoing-card .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.outgoing-card .stat-value {
  color: #f56c6c;
}

.total-card .stat-icon {
  background: rgba(118, 75, 162, 0.1);
  color: #764ba2;
}

.total-card .stat-value {
  color: #764ba2;
}

.content-row {
  margin-bottom: 20px;
}

.sync-history-card, .sync-config-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.config-form {
  padding: 20px 0;
}

.manual-sync {
  margin-top: 20px;
}

.error-text {
  color: #ff4d4f;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 5px;
}
</style>